後台
prog_custom.gs
//-------------------------------------------- 驗證
let rules = {};
let messages = {};
stru.forEach((element) => {
if (element.form_name && element.form_validate) {
const fieldRules = {};
const fieldMessages = {};
const fieldName = element.form_name;
const validations = element.form_validate.split('|');
validations.forEach((validation) => {
switch (validation) {
case '必填':
fieldRules.required = true;
fieldMessages.required = '必填';
break;
case 'email':
fieldRules.email = true;
fieldMessages.email = 'Email格式不正確';
break;
case '網址':
fieldRules.url = true;
fieldMessages.url = '網址格式不正確';
break;
case '數字':
fieldRules.number = true;
fieldMessages.number = '數字格式不正確';
break;
// 加入其他可能的驗證規則
}
});
if (Object.keys(fieldRules).length > 0) {
rules[fieldName] = fieldRules;
messages[fieldName] = fieldMessages;
}
}
});
rules = JSON.stringify(rules);
messages = JSON.stringify(messages);
//-------------------------------------------- 驗證end
樣版驗證改至後台
- 利用global 是全域變數的特性,將它傳遞至前台
//-------------------------------------------- js
global['js'] = `
$(function() {
$("#myForm").validate({
submitHandler: function(form) { //驗證成功執行
$('#submit').attr('disabled', true); //關閉送出
setIdAttribute('main-content', 'd-none'); //關閉主畫面
setIdAttribute('show', 'my-5'); //開啟loading畫面
insertData(); //寫入函式
document.getElementById('myForm').reset(); //表單重置
return false;
},
rules: ${rules},
messages: ${messages}
});
});
`;
樣版語法
<?!= global.js ?>